package online.heycm.platform.common.tools;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;

/**
 * @author heycm
 * @since 2023/12/2 10:06
 */
public class IPUtil {

    private static volatile String LOCAL_IP;

    private IPUtil() {}

    /**
     * 获取本地IP
     */
    public static String getLocalIP() {
        if (StringUtils.isBlank(LOCAL_IP)) {
            synchronized (IPUtil.class) {
                if (StringUtils.isBlank(LOCAL_IP)) {
                    try {
                        LOCAL_IP = getLocalIpAddress();
                    } catch (SocketException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return LOCAL_IP;
    }

    /**
     * 获取本地IP
     */
    public static String getLocalIpAddress() throws SocketException {
        Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
        while (networkInterfaces.hasMoreElements()) {
            NetworkInterface networkInterface = networkInterfaces.nextElement();
            if (!networkInterface.isUp()) {
                continue;
            }
            Enumeration<InetAddress> inetAddresses = networkInterface.getInetAddresses();
            while (inetAddresses.hasMoreElements()) {
                InetAddress inetAddress = inetAddresses.nextElement();
                if (inetAddress.isLinkLocalAddress() || inetAddress.isLoopbackAddress()
                        || inetAddress.isMulticastAddress()) {
                    continue;
                }
                return inetAddress.getHostAddress();
            }
        }
        return null;
    }

    /**
     * 获取网络请求IP
     *
     * @param request 请求
     */
    public static String getRemoteIpAddress(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_CLIENT_IP");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }
        return ipAddress;
    }
}
